package edu.software.PBL_Management_System.controller;

import edu.software.PBL_Management_System.entity.User;
import edu.software.PBL_Management_System.util.AliOssUtil;
import edu.software.PBL_Management_System.util.DemandUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//本质是用户服务里的头像模块
@RestController
@RequestMapping("/api/user")
@Slf4j
public class AverageController {

    private static final Logger logger = LoggerFactory.getLogger(AverageController.class);

    @Resource
    private DemandUtil demandUtil;

    @Value("${file.upload.path}")
    private String baseUploadPath;

    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("avatar") MultipartFile file,
                                          @RequestParam("userId") Long userId) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                        "error", "文件为空",
                        "message", "请选择要上传的头像文件"
                ));
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResponseEntity.badRequest().body(Map.of(
                        "error", "文件类型错误",
                        "message", "只支持图片文件"
                ));
            }

            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return ResponseEntity.badRequest().body(Map.of(
                        "error", "文件名无效",
                        "message", "无法获取文件名"
                ));
            }

            // 截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 为每个用户创建唯一的头像文件名，包含用户ID以便管理
            String objectName = "avatars/" + userId + "/" + UUID.randomUUID().toString() + extension;

            // 上传文件到阿里云OSS
            String avatarUrl = aliOssUtil.upload(file.getBytes(), objectName);

            logger.info("Avatar uploaded successfully for user {}: {}", userId, avatarUrl);

            // 更新用户头像URL到数据库
            User user = demandUtil.getUserById(userId);
            if (user == null) {
                return ResponseEntity.badRequest().body(Map.of(
                        "error", "用户不存在",
                        "message", "找不到指定的用户"
                ));
            }

            user.setAvatarUrl(avatarUrl);
            demandUtil.updateUser(user);

            // 构建响应
            Map<String, String> response = new HashMap<>();
            response.put("avatarUrl", avatarUrl);
            response.put("message", "头像上传成功");

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            logger.error("头像上传失败 - 用户ID: {}", userId, e);
            return ResponseEntity.badRequest().body(Map.of(
                    "error", "文件上传失败",
                    "message", e.getMessage()
            ));
        } catch (Exception e) {
            logger.error("头像上传过程中发生意外错误 - 用户ID: {}", userId, e);
            return ResponseEntity.internalServerError().body(Map.of(
                    "error", "操作失败",
                    "message", e.getMessage()
            ));
        }
    }

    /**
     * 获取用户头像URL
     * @param userId
     * @return
     */

    // 头像现在直接通过OSS的URL访问
    @GetMapping("/avatar/{userId}")
    public ResponseEntity<?> getAvatarUrl(@PathVariable Long userId) {
        try {
            User user = demandUtil.getUserById(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }

            String avatarUrl = user.getAvatarUrl();
            if (avatarUrl == null || avatarUrl.isEmpty()) {
                return ResponseEntity.notFound().build();
            }

            Map<String, String> response = new HashMap<>();
            response.put("avatarUrl", avatarUrl);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取用户头像URL失败 - 用户ID: {}", userId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
//    @PostMapping("/avatar")
//    public ResponseEntity<?> uploadAvatar(@RequestParam("avatar") MultipartFile file,
//                                          @RequestParam("userId") Long userId) {
//        try {
//            // 构建用户专属的头像目录
//            String userAvatarDir = baseUploadPath + File.separator + userId + File.separator + "avatar";
//            Path directoryPath = Paths.get(userAvatarDir);
//
//            // 如果目录不存在，创建目录
//            if (!Files.exists(directoryPath)) {
//                Files.createDirectories(directoryPath);
//            } else {
//                // 如果目录存在，删除旧头像
//                Files.list(directoryPath).forEach(oldFile -> {
//                    try {
//                        Files.delete(oldFile);
//                    } catch (IOException e) {
//                        logger.warn("Failed to delete old avatar: " + oldFile, e);
//                    }
//                });
//            }
//
//            // 获取文件扩展名
//            String originalFilename = file.getOriginalFilename();
//            String fileExtension = originalFilename != null ?
//                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
//
//            // 固定文件名为 avatar + 扩展名
//            String newFileName = "avatar" + fileExtension;
//
//            // 保存新文件
//            Path filePath = directoryPath.resolve(newFileName);
//            Files.copy(file.getInputStream(), filePath);
//
//            logger.info("File saved successfully at: " + filePath.toString());
//
//            // 构建访问URL（使用新的端点）
//            String avatarUrl = "/api/user/avatar/image/" + userId;
//
//            // 更新用户头像URL
//            User user = demandUtil.getUserById(userId);
//            user.setAvatarUrl(avatarUrl);
//            demandUtil.updateUser(user);
//
//            Map<String, String> response = new HashMap<>();
//            response.put("avatarUrl", avatarUrl);
//            response.put("message", "头像上传成功");
//
//            return ResponseEntity.ok(response);
//        } catch (IOException e) {
//            logger.error("File upload failed", e);
//            return ResponseEntity.badRequest().body(Map.of(
//                    "error", "文件上传失败",
//                    "message", e.getMessage()
//            ));
//        } catch (Exception e) {
//            logger.error("Unexpected error during file upload", e);
//            return ResponseEntity.badRequest().body(Map.of(
//                    "error", "操作失败",
//                    "message", e.getMessage()
//            ));
//        }
//    }
//
//    @GetMapping("/avatar/image/{userId}")
//    public ResponseEntity<?> getAvatar(@PathVariable Long userId) {
//        try {
//            String userAvatarDir = baseUploadPath + File.separator + userId + File.separator + "avatar";
//            Path directoryPath = Paths.get(userAvatarDir);
//
//            if (!Files.exists(directoryPath)) {
//                logger.warn("Avatar directory not found: " + directoryPath);
//                return ResponseEntity.notFound().build();
//            }
//
//            // 获取目录中的第一个文件（应该只有一个头像文件）
//            Path avatarPath = Files.list(directoryPath).findFirst().orElse(null);
//
//            if (avatarPath == null) {
//                logger.warn("No avatar file found in directory: " + directoryPath);
//                return ResponseEntity.notFound().build();
//            }
//
//            // 读取文件内容
//            byte[] imageBytes = Files.readAllBytes(avatarPath);
//
//            // 根据文件扩展名设置正确的Content-Type
//            String contentType = "image/jpeg"; // 默认为JPEG
//            String fileName = avatarPath.getFileName().toString().toLowerCase();
//            if (fileName.endsWith(".png")) {
//                contentType = "image/png";
//            } else if (fileName.endsWith(".gif")) {
//                contentType = "image/gif";
//            }
//
//            logger.info("Serving avatar for user " + userId + " with content type: " + contentType);
//            return ResponseEntity.ok()
//                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
//                    .body(imageBytes);
//
//        } catch (Exception e) {
//            logger.error("Failed to get avatar for user " + userId, e);
//            return ResponseEntity.internalServerError().build();
//        }
//    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/info")
    public ResponseEntity<?> getUserInfo(@RequestParam("userId") Long userId) {
        try {
            User user = demandUtil.getUserById(userId);
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("contact", user.getEmail());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("username", user.getUsername());

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            logger.error("Failed to get user info", e);
            return ResponseEntity.badRequest().body(Map.of(
                    "error", "获取用户信息失败",
                    "message", e.getMessage()
            ));
        }
    }
}
